package edu.whut.mall.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.whut.mall.admin.mapper.ResourcesMapper;
import edu.whut.mall.admin.mapper.RoleResourcesMapper;
import edu.whut.mall.admin.model.Resources;
import edu.whut.mall.admin.model.RoleResources;
import edu.whut.mall.admin.service.IResourceService;
import edu.whut.mall.common.mybatis.ParamsMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Author: smq
 * Unit: D9lab
 * Date: 2021-06-15 11.22
 */
@Service
@Slf4j
public class ResourceServiceImpl implements IResourceService {

    @Resource
    private ResourcesMapper resourcesMapper;

    @Resource
    private RoleResourcesMapper roleResourcesMapper;

    @Override
    public List<Resources> getResourcesByRoleId(int roleId) {
        return resourcesMapper.getResourcesByRoleId(roleId);
    }

    @Override
    public List<RoleResources> assignResourceRole(int roleId, String resourceIdString) {
        clearResourcesToRole(roleId);
        if(StringUtils.isNotBlank(resourceIdString)) {
            String[] resourceString = resourceIdString.split(",");
            int[] resourceIds= Arrays.stream(resourceString).mapToInt(Integer::parseInt).distinct().toArray();
            List<RoleResources> roleResourcesList =new ArrayList<>(resourceIds.length);
            Arrays.stream(resourceIds).forEach(id->{
                RoleResources roleResource= RoleResources.builder()
                        .roleId(roleId)
                        .resourcesId(id)
                        .isDeleted(0)
                        .createTime(new Date())
                        .build();
                roleResourcesList.add(roleResource);
                roleResourcesMapper.insert(roleResource);
            });
            return roleResourcesList;
        }
        else{
            return null;
        }
    }

    /**
     * 给角色指定资源之前先清空当前角色对应的资源
     * @param roleId
     */
    private void clearResourcesToRole(Integer roleId){
        ParamsMap map = ParamsMap.getPageInstance();
        map.put("roleId",roleId);
        map.put("updateTime",new Date());
        roleResourcesMapper.deleteAllByRoleId(map);
//        LambdaQueryWrapper<RoleResources> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(RoleResources::getRoleId,roleId);
//        List<RoleResources> roleResources = roleResourcesMapper.selectList(queryWrapper);
//        roleResources.forEach(roleResource -> {
//            roleResourcesMapper.deleteAllByRoleId(roleResource.getRoleId());
//        });
    }
}
